import React from 'react';
import {View, StyleSheet} from 'react-native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {NativeStackScreenProps} from '@react-navigation/native-stack';
import WebView from 'react-native-webview';
import {StackParamList} from '@/navigator';
import {useAsyncStorage} from '@react-native-async-storage/async-storage';
import NavigationBar from '@/components/NavigationBar';
import {useFlatListStore, type DataItem, type FlatListDataStore} from '@/store';

const FlatListDetail: React.FC<
  NativeStackScreenProps<StackParamList, 'FlatListDetail'>
> = props => {
  const {
    route: {
      params: {title, paragraph, desc, star, author, id, isSave, source},
    },
  } = props;
  const store = useFlatListStore();
  const insets = useSafeAreaInsets();
  const [saved, setSaved] = React.useState(isSave);
  const asyncStorage = useAsyncStorage('favorite');

  const htmlContent = `
  <!DOCTYPE html>
  <html>
  <head>
    <title>My Local HTML</title>
  </head>
  <body>
    <p>${paragraph}</p>
  </body>
  </html>
`;

  const handleUpdate = () => {
    if (source === 'Popular') {
      _update('data1', store.data1);
    } else if (source === 'Trending') {
      _update('data2', store.data2);
    } else if (source === 'Favorite') {
      _updateFavorite();
    }
  };

  const _updateFavorite = async () => {
    await _updateStorage();
    setSaved(!saved);
    const {data1, data2} = store;
    const newData1 = data1.map(item => {
      if (item.id === id) {
        return {
          ...item,
          isSave: !item.isSave,
        };
      }
      return item;
    });
    store.setStore('data1', newData1);
    const newData2 = data2.map(item => {
      if (item.id === id) {
        return {
          ...item,
          isSave: !item.isSave,
        };
      }
      return item;
    });
    store.setStore('data2', newData2);
  };

  const _updateStorage = async () => {
    // 更新本地存储
    const storage = await asyncStorage.getItem();
    let storageArr: DataItem[] = [];
    if (!!storage?.length) {
      storageArr = [...JSON.parse(storage)];
    }
    if (!saved) {
      // 收藏
      storageArr.push({
        id: id!,
        title: title!,
        desc: desc!,
        star: star!,
        paragraph: paragraph!,
        author: author!,
        isSave: !saved,
      });
    } else {
      // 取消收藏
      storageArr = storageArr.filter(item => item.id !== id);
    }
    await asyncStorage.setItem(JSON.stringify(storageArr));
  };

  const _update = async <K extends keyof FlatListDataStore>(
    key: K,
    data: DataItem[],
  ) => {
    await _updateStorage();
    // 更新store
    const newData = data.map(item => {
      if (item.id === id) {
        return {
          ...item,
          isSave: !item.isSave,
        };
      }
      return item;
    });
    setSaved(!saved);
    store.setStore(key, newData);
  };

  return (
    <View style={{marginBottom: insets.bottom, flex: 1}}>
      <NavigationBar
        showBackBtn
        showRightBtn
        title={title}
        isSave={saved}
        handleUpdate={handleUpdate}
      />
      <WebView source={{html: htmlContent}} style={{flex: 1}} />
    </View>
  );
};

export default FlatListDetail;

const styles = StyleSheet.create({});
